import Exception from '../utils/http-exception.js'
const { HttpException } = Exception

const errorHandler = async (ctx, next) => {
    try {
        await next()
    } catch (error) {
        // 开发环境
        const isHttpException = error instanceof HttpException
        const isDev = process.env.NODE_ENV === 'development'

        if (isDev && !isHttpException) {
            throw error
        }

        // 生产环境
        if (isHttpException) {
            ctx.body = {
                errcode: error.errcode,
                errmsg: error.msg
            }
            ctx.response.status = error.code
        } else {
            ctx.body = {
                errcode: 9999,
                errmsg: '未知错误！'
            }
            ctx.response.status = 500
        }
    }
}

export default errorHandler